#主模块import json
import os
from question_classifier import QuestionClassifier
from semantic_retriever import SemanticRetriever
from answer_generator import AnswerGenerator
from performance_timer import global_timer, StepTimer, APITimer
from multimodal_renderer import MultimodalRenderer
from context_manager import ContextManager
import json

class KnowledgeExplanationAgent:
    def __init__(self):
        self.classifier = QuestionClassifier()
        self.retriever = SemanticRetriever()
        self.generator = AnswerGenerator()
        self.renderer = MultimodalRenderer()
        self.context_manager = ContextManager()

    def process_question(self, user_id, question, session_id=None, preferred_model=None):
        """处理用户问题的完整流程"""
        try:
            # M1: 问题分类
            with StepTimer("问题分类"):
                classification = self.classifier.classify(question)
                global_timer.add_info("问题类型", classification['label'])
                print(f"问题分类: {classification}")
            
            # # M2: 语义检索（可选，当前知识库为空可跳过或返回空列表）
            # retrieved_docs = []  # 暂不使用知识库

            # M2: 语义检索
            with StepTimer("语义检索"):
                retrieved_docs = self.retriever.retrieve(question, classification['label'])
                global_timer.add_info("检索结果数量", len(retrieved_docs))
            
            # M5: 上下文管理
            with StepTimer("获取上下文"):
                context = self.context_manager.get_context(session_id or user_id)
            
            # M3: 回答生成
            with StepTimer("回答生成"):
                answer_markdown = self.generator.generate(
                    question=question,
                    classification=classification,
                    retrieved_docs=retrieved_docs,
                    context=context,
                    preferred_model=preferred_model
                )
            
            # M4: 更新上下文（记录对话历史）
            with StepTimer("更新上下文"):
                self.context_manager.update_context(
                    session_id or user_id,
                    question,
                    answer_markdown,
                    classification
                )
            
            # 只返回Markdown内容，不做多模态HTML渲染
            return {
                'status': 'success',
                'classification': classification,
                'answer_markdown': answer_markdown
            }
        except Exception as e:
            return {
                'status': 'error',
                'message': f'处理问题时出错: {str(e)}'
            }

if __name__ == "__main__":
    agent = KnowledgeExplanationAgent()
    
    print("=== 知识解释智能体系统 ===")
    print("支持的问题类型: definition, usage, error_debug, comparison, faq")
    print("输入 'exit' 退出\n")
    
    while True:
        user_id = input("用户ID: ")
        if user_id.lower() == 'exit':
            break
            
        question = input("问题: ")
        if question.lower() == 'exit':
            break
            
        result = agent.process_question(user_id, question)
        
        if result['status'] == 'success':
            print(f"\n=== 处理结果 ===")
            print(f"问题类型: {result['classification']['label']}")
            print(f"置信度: {result['classification']['confidence']:.3f}")
            print(f"\n=== 生成的回答 ===")
            print(result['answer_markdown'])
        else:
            print(f"错误: {result['message']}")
        
        print("\n" + "="*50 + "\n")